package rpc.core.plugin.impl.proxy;

import java.lang.reflect.Method;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.core.FlowReq;
import rpc.core.FlowRes;
import rpc.utils.ExceptionUtils;

/*********
 *
 *
 *@author 197
 *@date 2020/8/5 18:18
 *
 **/


public class RedisServiceProxy implements ServiceProxy {

  private static final Logger logger = LoggerFactory.getLogger(RedisServiceProxy.class);
  private RedisStringRedisTemplateServiceProxy redisServiceProxy;
  private Method method;
  private ExecutorService executorService;

  public RedisStringRedisTemplateServiceProxy getRedisServiceProxy() {
    return redisServiceProxy;
  }

  public RedisServiceProxy setRedisServiceProxy(RedisStringRedisTemplateServiceProxy redisServiceProxy) {
    this.redisServiceProxy = redisServiceProxy;
    return this;
  }

  public RedisServiceProxy setExecutorService(ExecutorService executorService) {
    this.executorService = executorService;
    return this;
  }

  public Method getMethod() {
    return method;
  }

  public RedisServiceProxy setMethod(Method method) {
    this.method = method;
    return this;

  }

  @Override
  public CompletableFuture<FlowRes> invoke(FlowReq req) {
    CompletableFuture<FlowRes> future = new CompletableFuture<>();
    executorService.execute(() -> {
      try {
        future.complete((FlowRes) method.invoke(redisServiceProxy, req));
      } catch (Exception e) {
        logger.error("exception:{} stackTrace:{}", e.getMessage(), ExceptionUtils.getTrace(e));
        future.complete(new FlowRes().fail(-817));
      }
    });

    return future;

  }
}